package com.sjzxywlkj.cplife.alipay.conn;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.sjzxywlkj.cplife.alipay.config.AlipayConfig;
import com.sjzxywlkj.cplife.alipay.request.entity.LoginToken;

/**
 * 应用授权
 */

public class LoginConn {

    //换取授权访问令牌
    //url:https://docs.open.alipay.com/api_9/alipay.system.oauth.token/
    public static String login(String code) throws AlipayApiException {

        AlipayClient alipayClient = AlipayConfig.aClient();
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(code);
        request.setGrantType("authorization_code");
        AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
        String userid = oauthTokenResponse.getUserId();
        return userid;
    }

    //换取应用授权令牌
    //url:https://docs.open.alipay.com/api_9/alipay.open.auth.token.app/
    public static AlipayOpenAuthTokenAppResponse token(LoginToken loginToken) throws AlipayApiException {

        AlipayClient alipayClient = AlipayConfig.aClient();
        AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
        request.setBizContent(loginToken.toJson());
        AlipayOpenAuthTokenAppResponse response = alipayClient.execute(request);
        return response;
    }
}
